<template>
<!-- 导航 -->
  <el-menu
    :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    background-color="#FFFFFF"
    text-color="#303133"
    active-text-color="#ffd04b"
    @select="handleSelect"
    router="true"
  >
    <el-menu-item class="logoItem" ><img src="../src/assets/kl_logo.png" style="height: 100px;width: 100px;" /></el-menu-item>
    <el-menu-item index="/">首页</el-menu-item>
    <el-menu-item index="/travel">景区</el-menu-item>
    <el-menu-item index="/weather">天气</el-menu-item>
    <el-menu-item index="/blog">动态</el-menu-item>
    <el-menu-item index="/notice">系统公告</el-menu-item>
    <el-menu-item index="/about">关于</el-menu-item>
    <div style="width: 1000px;"></div>
    <!-- 右侧的登录/注册和个人中心部分 -->
    <el-menu-item v-if="!userIsLogin()" @click="drawerLogin = true;getCaptchaImg()"><el-icon><Avatar /></el-icon>登录</el-menu-item>
    <el-menu-item v-if="!userIsLogin()" @click="toRegister">注册</el-menu-item>
    <el-menu-item index="/userInfo" v-if="userIsLogin()"><img :src="userInfo.avatar === '' ? require('@/assets/default_img.jpg') : userInfo.avatar" style="height: 50px;width: 50px;" /></el-menu-item>
    <el-menu-item index="/userInfo" v-if="userIsLogin()" >个人中心</el-menu-item>
    <el-menu-item v-if="userIsLogin()" @click="logout" >登出</el-menu-item>
  </el-menu>
  <router-view/>

<!-- 登录抽屉 -->
  <el-drawer
    v-model="drawerLogin"
    title="您好！欢迎登录"
    :direction="direction"
    :before-close="handleClose"
  >
    <!-- 表单 -->
    <el-form
      style="max-width: 700px"
      :model="loginData"
      status-icon
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名：">
        <el-input v-model="loginData.username" type="text" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密码：">
        <el-input v-model="loginData.password" type="password" show-password="true" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item label="验证码：">
        <div style="display: flex; align-items: center;">
          <el-input v-model="loginData.code" type="text" placeholder="请输入验证码" style="width: 200px;"/>
          <img :src="captchaUrl" alt="验证码" style="margin-left: 10px; height: 40px; width: 120px; cursor: pointer;" @click="getCaptchaImg" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">
          登录
        </el-button>
        <el-button @click="reset">重置</el-button>
        <el-link style="margin-left: 10px;" type="success" @click="toRegister">没有账号？点击前往注册</el-link>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { ref,reactive,onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
const activeIndex = ref('/')
const drawerLogin = ref(false)
const loginData = reactive({
  username:'',
  password:'',
  code:''
})

const loading = ref(false)

const captchaUrl = ref('')

const userInfo = ref(JSON.parse(sessionStorage.getItem('userInfo')))

onMounted(() => {
  const storedUserInfo = sessionStorage.getItem('userInfo');
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo);
  } else {
    userInfo.value = {}; // 如果没有用户信息，则设置为一个空对象
  }
});

// 判断用户信息是否为空
const userIsLogin = () => {
  return userInfo.value && Object.keys(userInfo.value).length > 0;
}

const logout = () => {
  userInfo.value = {}; // 设置为空对象，确保类型一致
  //清除sessionStorage
  sessionStorage.removeItem('userInfo')
  window.location.href = "/"
}

const getCaptchaImg =  () => {
  loading.value = true
  axios.get('/api/user/captcha',{responseType: 'arraybuffer' }).then(res => {
     // 将 ArrayBuffer 转换为 Base64 格式
    const base64Image = arrayBufferToBase64(res.data);
          // 设置图片的 URL（Base64 格式）
    captchaUrl.value = `data:image/png;base64,${base64Image}`;
  }).catch(err => {
    ElMessage({
      message: '获取验证码失败！请重试！',
      type: 'error',
    })
  })
}

// 将 ArrayBuffer 转换为 Base64 字符串的函数
const arrayBufferToBase64 = (buffer) => {
      let binary = '';
      const bytes = new Uint8Array(buffer);
      const len = bytes.byteLength;
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary); // 使用 btoa() 转换为 Base64
    };

const handleSelect = (key) => {
  console.log(key)
}

//跳转到注册页面
const toRegister = function(){
   // 打开新窗口并跳转到注册页面
   window.location.href = "register.html"
}

const login = function() {
  if (loginData.username === '' || loginData.username.length === 0) {
    ElMessage({
      message: '用户名不能为空！',
      type: 'warning',
    })
  }else if(loginData.password === '' || loginData.password.length === 0){
    ElMessage({
      message: '密码不能为空！',
      type: 'warning',
    })
  }else if(loginData.code === '' || loginData.code.length === 0){
    ElMessage({
      message: '验证码不能为空！',
      type: 'warning',
    })
  }else{
    //1.发送网络请求
    axios.post('/api/user/login',loginData).then(res => {
      if(res.data.code === 200){
        userInfo.value = res.data.data
        drawerLogin.value = false
        //保存用户信息到sessionStorage
        sessionStorage.setItem('userInfo',JSON.stringify(userInfo.value))
        //跳转到用户信息页面
        window.location.href = '/userInfo'
      }else{
        ElMessage({
          message: res.data.message,
          type: 'error',
        })
      }
    }).catch(err => {
      ElMessage({
        message: err.response.data.message,
        type: 'error',
      })
    })
  }
  getCaptchaImg()
}

const reset = function(){
  loginData.uname = '';
  loginData.pwd = '';
  loginData.code = '';
}
</script>

  <!-- <nav>
    <router-link to="/">主页</router-link> |
    <router-link to="/about">关于</router-link>
  </nav>
  <router-view/> -->

<style>
.el-menu--horizontal {
  --el-menu-horizontal-height: 100px;
}
/* .el-menu--horizontal > .el-menu-item:nth-child(7) {
  margin-right: auto;
} */
.logoItem{
  pointer-events: none; /* 让元素不响应鼠标事件，达到不可点击的效果 */
  opacity: 1!important; /* 强制将透明度设置为1，避免变灰，这里加!important是为了确保能覆盖默认样式 */
}
</style>